#include "stdafx.h"
#include "net/PartSource.hpp"
#include "filesys/file.hpp"
#include "filesys/path.hpp"
using JHCPP::filesys::CFile;
using JHCPP::filesys::CPath;
#include "stdlib/exception.hpp"
using JHCPP::stdlib::jhException::OpenFileException;

NET_NAMESPACE_BEGIN

static const std::string EMPTY;
const int CPartSource::UNKNOWN_CONTENT_LENGTH = -1;

CPartSource::CPartSource() : m_mediaType("application/octet-stream")
{
}

CPartSource::CPartSource(const std::string& mediaType) : m_mediaType(mediaType)
{
}

CPartSource::~CPartSource()
{
}

const std::string& CPartSource::mediaType() const
{
	return m_mediaType;
}

const std::string& CPartSource::filename() const
{
	return EMPTY;
}

CMessageHeader& CPartSource::headers()
{
	return m_headers;
}

const CMessageHeader& CPartSource::headers() const
{
	return m_headers;
}

std::streamsize CPartSource::getContentLength() const
{
	return UNKNOWN_CONTENT_LENGTH;
}


CFilePartSource::CFilePartSource(const std::string& path):
m_path(path), m_istr(path)
{
	CPath p(path);
	m_filename = p.getFileName();
	if (!m_istr.good())
		throw OpenFileException(path);
}

CFilePartSource::CFilePartSource(const std::string& path, const std::string& mediaType)
: CPartSource(mediaType),
m_path(path),
m_istr(path)
{
	CPath p(path);
	m_filename = p.getFileName();
	if (!m_istr.good())
		throw OpenFileException(path);
}

CFilePartSource::CFilePartSource(const std::string& path, const std::string& filename, const std::string& mediaType)
: CPartSource(mediaType),
m_path(path),
m_filename(filename),
m_istr(path)
{
	CPath p(path);
	if (!m_istr.good())
		throw OpenFileException(path);
}

CFilePartSource::~CFilePartSource()
{
}

std::istream& CFilePartSource::stream()
{
	return m_istr;
}

const std::string& CFilePartSource::filename() const
{
	return m_filename;
}

std::streamsize CFilePartSource::getContentLength() const
{
	CFile p(m_path);
	return (std::streamsize)p.getSize();
}

NET_NAMESPACE_END
